<?php
/**
 * 推荐位管理
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/26
 * Time: 11:33
 */

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\BoolStatus;
use app\common\model\Position as PositionModel;
use app\admin\validate\Position as PositionValidate;
use think\Db;

class Position extends AdminBase
{
    /**
     * 推荐位列表
     * @return mixed
     */
    public function index()
    {
        $positionModel = new PositionModel();
        $list          = $positionModel->paginate($this->pageSize);

        // 获取分页显示
        $page = $list->render();
        // 模板变量赋值
        $this->assign('list', $list);
        $this->assign('page', $page);

        $status = BoolStatus::getLables();
        $this->assign('status', $status);
        return $this->fetch('position/index');
    }


    /**
     * 设置推荐位信息
     */
    public function set()
    {
        $id            = $this->request->param('id');
        $positionModel = new PositionModel();
        if ($this->request->isPost()) {
            $name        = $this->request->param('name');
            $status      = $this->request->param('status', BoolStatus::OPEN, 'int');
            $description = $this->request->param('description');

            //验证数据
            $validate = new PositionValidate();
            if (!$validate->check(['name' => $name, 'status' => $status])) {
                $this->error($validate->getError());
            }

            $currentTime = time();
            if (!$id) {
                $positionModel->created_time = $currentTime;
            } else {
                $positionModel = $positionModel::find($id);
            }
            $positionModel->name         = $name;
            $positionModel->status       = $status;
            $positionModel->updated_time = $currentTime;
            $positionModel->description  = $description;
            $result                      = $positionModel->save();
            if (!$result) {
                $this->error('操作失败~~~');
            }
            $this->success('操作成功~~', url('admin/position/index'));
        }
        $position = null;
        if ($id) {
            $position = $positionModel::find($id);
        }

        $this->assign('position', $position);
        //开关
        $status = BoolStatus::getLables();
        $this->assign('status', $status);

        return $this->fetch('position/set');
    }

}